package com.yocard.yxyd.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.webkit.ValueCallback;
import android.widget.ImageView;

import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yocard.yxyd.R;
import com.yocard.yxyd.utils.util.ToastUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created on 2019/5/29
 * 二维码海报
 */
public class QrCodeDialog extends Dialog {

    private final ValueCallback<String> callback;
    private String url;
    private Bitmap mBitmap;
    Handler mHandler;

    public QrCodeDialog(@NonNull Context context, ValueCallback<String> callback, String url) {
        super(context, R.style.QrDialogStyle);
        this.callback = callback;
        this.url = url;
        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_qr_code);
        setCanceledOnTouchOutside(true);
        int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 70, getContext().getResources().getDisplayMetrics());

        ImageView imageView = findViewById(R.id.iv_qr_code);
        mBitmap = CodeUtils.createImage(url, width, width, BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.ico_share));
        imageView.setImageBitmap(mBitmap);
    }

    @Override
    public void show() {
        super.show();
        if (TextUtils.isEmpty(url)) return;
        View view = findViewById(R.id.iv_share_bg);
        save(view);
    }

    @Override
    public void dismiss() {
        if (mBitmap != null)
            mBitmap.recycle();
        mBitmap = null;
        super.dismiss();
    }

    private void save(final View mView) {
        // 获取图片某布局
        mView.buildDrawingCache();
        mView.setDrawingCacheEnabled(true);

        mHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                // 要在运行在子线程中
                mBitmap = mView.getDrawingCache(); // 获取图片
                savePicture(mBitmap, "zzp_sale.png");// 保存图片
                mView.destroyDrawingCache(); // 保存过后释放资源
            }
        }, 500);
    }

    public void savePicture(Bitmap bm, String fileName) {
        if (null == bm) {
            return;
        }
        //建立指定文件夹
        File foder = new File(Environment.getExternalStorageDirectory(), "zzp_sale");
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(foder, fileName);
        try {
            if (!myCaptureFile.exists()) {
                myCaptureFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            //压缩保存到本地
            bm.compress(Bitmap.CompressFormat.JPEG, 90, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(getContext().getContentResolver(),
                    myCaptureFile.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".fileprovider", myCaptureFile);
        } else {
            uri = Uri.fromFile(myCaptureFile);
        }
        getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));

        ToastUtils.showShort("保存成功!");

    }
}
